#include "../../../common/etcd.hpp"
#include "../../../common/channel.hpp"
#include <gflags/gflags.h>
#include "message.pb.h"

DEFINE_bool(run_mode, false, "程序的运行模式,false-调试； true-发布；");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(instance_name, "/echo/instance", "当前实例名称");
DEFINE_string(access_host, "127.0.0.1:7070", "当前实例的外部访问地址");
DEFINE_string(call_service, "/service/echo", "服务监控根目录");

// void online(const std::string& serviceName, const std::string& serverHost)
// {
//     LOG_DEBUG("上线服务:{}-{}",serviceName,serverHost);
// }


// void offline(const std::string& serviceName, const std::string& serverHost)
// {
//     LOG_DEBUG("下线服务:{}-{}",serviceName,serverHost);
// }

int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    initLogger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    //1.构造rpc信道管理对象
    auto sm = std::make_shared<ServiceChannelManager>();
    sm->declared(FLAGS_call_service);

    //2.etcd构建服务发现对象
    auto put_cb = std::bind(&ServiceChannelManager::onServiceUpline,sm.get(),std::placeholders::_1,std::placeholders::_2);
    auto del_cb = std::bind(&ServiceChannelManager::onServiceDownline,sm.get(),std::placeholders::_1,std::placeholders::_2);
    my::Discovery::ptr dclient = std::make_shared<my::Discovery>(FLAGS_etcd_host,FLAGS_base_service,put_cb,del_cb);

    // if (!channel)
    // {
    //     std::this_thread::sleep_for(std::chrono::seconds(1));
    //     return -1;
    // }

    //4.发起RPc调用
    while (1)
    {
        // 3.通过rpc信道，获取提供Echo服务的信道
        auto channel = sm->choose(FLAGS_call_service);
        if (!channel)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            continue;
            // return -1;
        }
        my::EchoService_Stub stub(channel.get());
        my::EchoRequest req;
        req.set_message("你好rpc!!!!!");
        // 添加上下文管理对象
        brpc::Controller *controller = new brpc::Controller();
        my::EchoResponse *rsp = new my::EchoResponse();
        stub.Echo(controller, &req, rsp, nullptr);
        if (controller->Failed())
        {
            std::cout << "Rpc调用失败:" << controller->ErrorText() << std::endl;
            delete controller;
            delete rsp;
            std::this_thread::sleep_for(std::chrono::seconds(1));
            continue;
            // return -1;
        }

        std::cout << "收到响应:" << rsp->message() << std::endl;
        break;
    }

    // std::this_thread::sleep_for(std::chrono::seconds(600));
}
